package com.example.springboot.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.springboot.common.ResultCode;
import com.example.springboot.common.config.JwtTokenUtils;
import com.example.springboot.dao.Order_ofDao;
import com.example.springboot.entity.Account;
import com.example.springboot.entity.Order_of;
import com.example.springboot.entity.User;
import com.example.springboot.exception.CustomException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class Order_ofService {
    @Resource
    Order_ofDao order_ofDao;
    public List<Order_of> GetAll() {
        return order_ofDao.selectAll();
    }


    public Order_of findById(Integer id) {

        return order_ofDao.findById(id);
    }

    public Order_of order_ofRegister(Order_of order_of) {

        String userName = order_of.getUserName();
//     1.先校验用户名是不是为空： 如果用户名，为空，抛出异常
        if (ObjectUtil.isEmpty(userName)){
            throw new CustomException(ResultCode.USERNAME_ISNULL);
        }
//     2.校验用户名的唯一性：
        Order_of dbOrder_of = order_ofDao.findByName(userName);
        if (ObjectUtil.isNotEmpty(dbOrder_of)) {
            throw new CustomException(ResultCode.USER_EXIST_ERROR);
        }
        order_ofDao.insertSelective(order_of);
        return order_of;
    }

    public void delete(Integer id) {
        order_ofDao.deleteByPrimaryKey(id);
    }



    public Order_of order_ofEdit(Order_of order_of) {

        String userName = order_of.getUserName();
//     校验用户名是不是为空： 如果用户名，为空，抛出异常
        if (ObjectUtil.isEmpty(userName)){
            throw new CustomException(ResultCode.USERNAME_ISNULL);
        }
        order_ofDao.updateByPrimaryKeySelective(order_of);

        return order_of;
    }

    // 分页查询和模糊查询的方法
    //PageInfo 里面装的是分页后分装的数据，返回值也要用PageInfo.of()包裹
    public PageInfo<Order_of> findPage(Order_of search, Integer pageNum, Integer pageSize) {
        //获取当前用户，判断当前用户是否处于登录状态
        Account user = JwtTokenUtils.getCurrentUser();//获取当前用户
        if (ObjectUtil.isEmpty(user)) {
            throw new CustomException(ResultCode.USER_NOT_LOGIN);
        }
        // 开启分页（开启分页后一定是操作数据库）
        PageHelper.startPage(pageNum, pageSize);
        List<Order_of> all = findByCondition(search);

        return PageInfo.of(all);
    }

    // 根据条件查询的方法
    public List<Order_of> findByCondition(Order_of search) {
        return order_ofDao.findBySearch(search);
    }

}